package com.zzl.bonds.ticket.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzl.bonds.ticket.constant.type.FlowChartTypeEnum;
import com.zzl.bonds.ticket.dao.TicketFlowChartDao;
import com.zzl.bonds.ticket.dto.TicketFlowChartDto;
import com.zzl.bonds.ticket.entity.TicketFlowChartEntity;
import com.zzl.bonds.ticket.service.TicketFlowChartService;
import com.zzl.bonds.ticket.service.TicketOpenService;
import com.zzl.bonds.ticket.service.TicketService;
import com.zzl.bonds.ticket.service.TicketTransferService;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.serurity.entity.User;
import com.zzl.general.common.utils.QmBeanUtils;
import com.zzl.general.common.utils.Tools;
import com.zzl.general.common.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 流程图表
 *
 * @author sunpp
 * @date 2022-02-16 11:14:07
 */
@Slf4j
@Service("ticketFlowChartService")
public class TicketFlowChartServiceImpl extends ServiceImpl<TicketFlowChartDao, TicketFlowChartEntity> implements TicketFlowChartService {
    @Autowired
    private TicketOpenService ticketOpenService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private TicketTransferService ticketTransferService;

    /**
     * 开立详情票据流转图总的
     *
     * @param ticketOpenId
     * @return
     * @throws SysException
     */
    @Override
    public List<TicketFlowChartDto> openSignAll(String ticketOpenId) throws SysException {
        /*TODO*/
        List<TicketFlowChartEntity> list = this.listByTicketOpenId(ticketOpenId);
        List<TicketFlowChartDto> list1 = QmBeanUtils.copyListProperties(list,TicketFlowChartDto::new);
        return getTreeList(list1);
        /*TicketFlowChartEntity ticketFlowChartEntity = this.getOneByOpenTicketId (ticketOpenId);
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getId, ticketFlowChartEntity.getParentId())
                .or().eq(TicketFlowChartEntity::getApplyId, ticketFlowChartEntity.getApplyId());
        List<TicketFlowChartEntity> list = this.list(queryWrapper);
        list.forEach(
                e -> {
                    if (!e.getApplyId().equals(ticketFlowChartEntity.getApplyId())) {
                        e.setParentId("0");
                    }
                }
        );
        List<TicketFlowChartDto> dtos = QmBeanUtils.copyListProperties(list, TicketFlowChartDto::new);
        return getTreeList(dtos);*/

    }

    /**
     * 查询开单的票据轨迹
     *
     * @param ticketOpenId 开立id
     * @return 流转轨迹
     */
    @Override
    public TicketFlowChartEntity getOneByOpenTicketId(String ticketOpenId) {
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getTicketOpenId, ticketOpenId)
                .eq(TicketFlowChartEntity::getType, FlowChartTypeEnum.OPEN.getCode());
        List<TicketFlowChartEntity> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return new TicketFlowChartEntity();
        }
        return list.get(0);
    }

    /**
     * 我的票据详情票据流转图
     *
     * @param ticketId
     * @return
     * @throws SysException
     */
    @Override
    public List<TicketFlowChartDto> ticketFlowChart(String ticketId) throws SysException {
        TicketFlowChartEntity ticketFlowChartEntity = this.getOneByTicketId(ticketId);
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getId, ticketFlowChartEntity.getParentId())
                .or().eq(TicketFlowChartEntity::getApplyId, ticketFlowChartEntity.getApplyId());
        List<TicketFlowChartEntity> list = this.list(queryWrapper);
        list.forEach(
                e -> {
                    if (!e.getApplyId().equals(ticketFlowChartEntity.getApplyId())) {
                        e.setParentId("0");
                    }
                }
        );
        List<TicketFlowChartDto> dtos = QmBeanUtils.copyListProperties(list, TicketFlowChartDto::new);
        return getTreeList(dtos);
    }

    @Override
    public TicketFlowChartEntity getLastIdForTicketId(String ticketId) {
        return baseMapper.findFirstByTicketId(ticketId);
    }

    @Override
    public void saveTicketFlowChartEntity(List<TicketFlowChartEntity> ticketFlowChartEntitys, User user) throws SysException {
        ticketFlowChartEntitys.forEach(e -> {
            e.setId(UuidUtils.UUID());
            e.setCreatorId(user.getId());
        });
        if (!this.saveBatch(ticketFlowChartEntitys)) {
            throw new SysException("新增失败！");
        }
    }

    @Override
    public TicketFlowChartEntity getOneByTicketId(String ticketId) {
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getTicketId, ticketId);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<TicketFlowChartEntity> listByTicketOpenId(String ticketOpenId) {
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getTicketOpenId, ticketOpenId);
        return this.list(queryWrapper);
    }

    @Override
    public List<TicketFlowChartEntity> listByTicketIds(List<String> ticketIds) {
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(TicketFlowChartEntity::getTicketId, ticketIds);
        return this.list(queryWrapper);
    }

    /**
     * 转让申请详情票据流转图
     *
     * @param transferId
     * @return
     * @throws SysException
     */
    @Override
    public List<TicketFlowChartDto> transferFlowChart(String transferId) throws SysException {
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getApplyId, transferId);
        List<TicketFlowChartEntity> list = this.list(queryWrapper);
        TicketFlowChartDto ticketFlowChartDto = new TicketFlowChartDto();
        if (!CollectionUtil.isEmpty(list)) {
            QueryWrapper<TicketFlowChartEntity> parentQueryWrapper = new QueryWrapper<>();
            parentQueryWrapper.lambda().eq(TicketFlowChartEntity::getId, list.get(0).getParentId());
            TicketFlowChartEntity parentEntity = this.getOne(parentQueryWrapper);
            BeanUtils.copyProperties(parentEntity, ticketFlowChartDto);
            List<TicketFlowChartDto> dtos = QmBeanUtils.copyListProperties(list, TicketFlowChartDto::new);
            ticketFlowChartDto.setParentId("0");
            ticketFlowChartDto.setChildren(dtos);
        }
        return Collections.singletonList(ticketFlowChartDto);
    }

    /**
     * 开立签收详情票据流转图
     *
     * @param ticketOpenId
     * @return
     * @throws SysException
     */
    @Override
    public List<TicketFlowChartDto> openSign(String ticketOpenId) {
        QueryWrapper<TicketFlowChartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TicketFlowChartEntity::getTicketOpenId, ticketOpenId);
        queryWrapper.orderByAsc("create_time").last("limit 0,2");
        List<TicketFlowChartEntity> list = this.list(queryWrapper);
        List<TicketFlowChartDto> dtos = QmBeanUtils.copyListProperties(list, TicketFlowChartDto::new);
        return getTreeList(dtos);
    }


    /**
     * 传入所有的数据
     *
     * @param rawTreeNodeList
     * @return
     */
    public List<TicketFlowChartDto> getTreeList(List<TicketFlowChartDto> rawTreeNodeList) {
        List<TicketFlowChartDto> treeNodeList = new ArrayList<>();
        Iterator<TicketFlowChartDto> it = rawTreeNodeList.iterator();
        while (it.hasNext()) {
            TicketFlowChartDto treeNode = it.next();
            String parentId = treeNode.getParentId();
            // 判断是否是最顶级节点
            boolean isRootNode = "0".equals(parentId)
                    || Tools.isEmpty(parentId);
            if (isRootNode) {
                it.remove();
                treeNodeList.add(treeChild(treeNode, rawTreeNodeList));
            }
        }
        return treeNodeList;
    }

    /**
     * 递归设置子节点
     *
     * @param node
     * @param rawTreeNodeList
     * @return
     */
    private TicketFlowChartDto treeChild(TicketFlowChartDto node, List<TicketFlowChartDto> rawTreeNodeList) {
        String id = node.getId();
        List<TicketFlowChartDto> children = new ArrayList<>();
        Iterator<TicketFlowChartDto> it = rawTreeNodeList.iterator();
        while (it.hasNext()) {
            TicketFlowChartDto treeNode = it.next();
            String parentId = treeNode.getParentId();
            if (!Tools.isEmpty(parentId)) {
                if (id.equals(parentId)) {
                    children.add(treeNode);
                    treeChild(treeNode, rawTreeNodeList);
                }
            }
            //填充子节点
            node.setChildren(children);
        }
        return node;
    }
}